﻿using System.Text;
using System.Net;

namespace CometDocs
{
    /// <summary>
    /// .Net interface for the CometDocs web API.
    /// It is not thread-safe as the underlying WebClient is not.
    /// </summary>
    internal partial class Client : IClient
    {
        private const string APIRoot = "https://www.cometdocs.com/api/v1/";

        /// <summary>
        /// The encoding used by the CometDocs API.
        /// </summary>
        private static readonly Encoding encoding = Encoding.ASCII;

        /// <summary>
        /// The WebClient used to emit all the HTTP(S) requests to the CometDocsAPI.
        /// </summary>
        private readonly WebClient webClient = new WebClient();

        /// <summary>
        /// Check if the response represents a successful operation or a failure.
        /// It throws a CometDocsException in case of failure.
        /// </summary>
        /// <param name="response">The Response object to check</param>
        private void CheckAndThrow(Response response)
        {
            if (response.Status != Status.OK)
            {
                if (response.Status == Status.InvalidToken)
                {
                    throw new InvalidTokenException(response.Message, response.Status, response.Error);
                }

                throw new CometDocsException(response.Message, response.Status, response.Error);
            }
        }
    }
}
